// StepsPage.jsx  
import React, { useState,useEffect } from 'react';  
import { Steps, Button,Spin, Card } from 'antd';  
import BasicInfoForm from '../step/step1';  
import FileUpload from '../step/step2';  
import Step3 from '../step/step3';  
import {useTranslation} from 'react-i18next'
import { template,add,editProduct,addFm,editFm,subjectTestResult,updateSubjectTestResult,createReport,separatedFm,separatedFix,separatedCreateReport,mixedfm,mixedFix,mixedCreateReport,getRmInciResult,saveSafetyRmInciResult,batchSaveRmInciResult,updateDataResult,uploadRemark,uploadRemarkUpdate,delRemark,refreshResult} from "@/api/modules/jhreport";
import FullscreenLoading from '@/components/FullscreenLoading';
import { FormOutlined ,ArrowUpOutlined,TableOutlined,FileTextOutlined,CloudUploadOutlined,CloudDownloadOutlined} from '@ant-design/icons'; 
import useCacheAlive from '@/hooks/useCacheAlive';
const { Step } = Steps;  
  
const fmScreening = () => {  
  const { t } = useTranslation();
  const [current, setCurrent] =  useCacheAlive(0, `table-fmscreening-Current`)
  const [step2formValues, setFormValues] = useCacheAlive({}, `table-fmscreening-step2FormValues`) 
  const [step2Table, setStep2Table] =  useCacheAlive([], `table-fmscreening-step2Table`)   
  const [step3formValues, setStep3FormValues] = useCacheAlive({}, `table-fmscreening-step3formValues`) 
  const [safety_product_id, setSafety_product_id] =  useCacheAlive({}, `table-fmscreening-safetyProductId`)
  const [loading, setLoading] = useState(false); 
  const [step1Value, setStep1] =  useCacheAlive({}, `table-fmscreening-step1Value`)

  useEffect(() => { 
     let productId  =  getQueryVariable("productId")
      if (productId) {  
        // 使用productId进行某些操作，比如发起请求获取产品数据  
        setSafety_product_id(productId)
        // fetchProductData(productId);  
      } else {  
        setSafety_product_id(0)
      }  
    }, []); // 当productId变化时，这个effect会重新运行  

 const getQueryVariable = (variable) =>{
  const query = window.location.search.substring(1);
  const vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split("=");
      if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}

  const handleNext = (phase,rawData) => {  
    if(phase == '1'){
      if(rawData !== ''){
        setStep2Table(rawData)
      }
      setCurrent(1);  
    }else if(phase == '2'){
      setStep3FormValues(rawData)
      // setReport_id(rawData.id)
      setCurrent(2);  
    }
  };  
  

  
  const handleFinish = (values) => {  
      console.log(values,'values')
      // 当表单提交时，设置表单值并推进到下一步  
      setLoading(true);  // 开始加载时设置为 true  
      setFormValues(values);
      const form1 = values
      setStep1(form1);  
      if (Array.isArray(values.position) && values.position.length > 0) {  
        values.position = values.position.join("，");  
      }  
      if (Array.isArray(values.efficacy) && values.efficacy.length > 0) {  
        values.efficacy = values.efficacy.join("，");  
      } 
      if (Array.isArray(values.form) && values.form.length > 0) {  
        values.form = values.form.join("，");  
      } 
      if (Array.isArray(values.method) && values.method.length > 0) {  
        values.method = values.method.join("，");  
      } 
      if (Array.isArray(values.population) && values.population.length > 0) {  
        values.population = values.population.join("，");  
      } 
      if (Array.isArray(values.people) && values.people.length > 0) {  
        values.people = values.people.join("，");  
      } 
      //暴露量特殊处理，使用英文逗号
      if (Array.isArray(values.classification) && values.classification.length > 0) {  
        values.classification = values.classification.join(","); 
      } 
    
      values.productStatus='NoApproval'
      values.fm_number= values.productCode
      setFormValues(values)
      handleNext('1','')
      setLoading(false); 
  };  
  
  const renderContent = (current) => {  
    switch (current) {  
      case 0:  
        return <BasicInfoForm onFinish={handleFinish} productId={safety_product_id} step1Value={step1Value}/>;  
      case 1:  
        return <FileUpload formData={step2formValues} tableData={step2Table} onUploadSuccess={handleNext} />;  
      case 2:
        return <Step3 formData={step3formValues} onUploadSuccess={handleNext} ></Step3>
      default:  
        return '完成';  
    }  
  };  

  const handleStepClick = (index) => {  
    // 只允许点击小于或等于当前步骤的步骤  
    if (index < current) { 
      if(index==0){
        setCurrent(index); 
      }else if(index==1){
        // handleFinish(orignStepValue)
        setLoading(true);  // 开始加载时设置为 true 
        console.log(step2formValues,'data')
        let rawData = step2formValues
        editProduct(rawData).then(res=>{
          if(res.code==200){
            setFormValues(rawData)
            if(res.data.data[0] !== ''){
              setStep2Table(res.data.data[0])
            }
            setCurrent(1); 
            setLoading(false); 
          }
        })
      }
      // 在这里可以添加跳转到对应步骤内容的逻辑，比如更新状态、导航等  
    }  
  }; 
  
  return (  
    <div>  
      <FullscreenLoading showLoading={loading} loadingTip="Loading..."/> 
      <Card>
        <Steps current={current} >  
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(0)} title={t('inputReportDetail')} icon={<FormOutlined />}/>  
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(1)} title={t('report.FormulaCompositionUpload')} icon={<ArrowUpOutlined/>}/>  
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(2)} title={t('report.ScreeningResults')} icon={<TableOutlined />}/>  
        </Steps> 
      </Card>
       
      <div style={{ marginTop: 16 }}>{renderContent(current)}</div>  
     
    </div>  
  );  
};  
  
export default fmScreening;